package org.atovio.coolexam.service.impl;

import org.atovio.coolexam.entity.Subject;
import org.atovio.coolexam.exception.ServiceException;
import org.atovio.coolexam.mapper.SubjectMapper;
import org.atovio.coolexam.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional
public class SubjectServiceImpl implements SubjectService {

    private final SubjectMapper subjectMapper;

    @Autowired
    public SubjectServiceImpl(SubjectMapper subjectMapper) {
        this.subjectMapper = subjectMapper;
    }

    @Override
    public int getCount(Map<String, Object> criteria) {
        return subjectMapper.selectCountSelective(criteria);
    }

    @Override
    public List<Subject> getAllSubject() {
        return subjectMapper.selectSelective(Map.of());
    }

    @Override
    public void deleteById(int id) {
        int count = subjectMapper.deleteById(id);
        if (count != 1)
            throw new ServiceException("数据库内部错误");
    }

    @Override
    public List<Subject> getLikeUserName(String name) {
        return subjectMapper.selectSelective(Map.of("name", name));
    }

    @Override
    public Subject update(Subject subject) {
        int count = subjectMapper.update(subject);
        if (count != 1)
            throw new ServiceException("数据库内部错误");
        return subjectMapper.selectById(subject.getId());
    }

    @Override
    public Subject getById(int id) {
        return subjectMapper.selectById(id);
    }

    @Override
    public void addSubject(Subject subject) {
        int count = subjectMapper.insert(subject);
        if (count != 1)
            throw new ServiceException("数据库内部错误");
    }
}
